package be.dataflow.xtime;

import java.util.Random;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import be.dataflow.xtime.DFHttpClient.ApiException;

public class XtimeActivity extends Activity implements View.OnClickListener {

	public static final String baseurl = "http://trace.copywaste.org/";
	public static final int PERIOD = 300000; // 5 minutes

	/**
	 * unique identifiers for context menu items
	 */
	private static final int ACTIVITY_PREFERENCES = 1;
	private static final int MENU_DIALOG = 2;
	private static final int MENU_TOAST = 3;
	private static final int MENU_NOTIFICATION = 4;
	private static final int DIALOG_FROM_LIST = 5;
	private static final int HELLO_ID = 6;

	/**
	 * reference to preferences
	 */
	private static SharedPreferences prefs;

	/**
	 * property that can be set by user in preferences activity
	 */
	private boolean showLifeCycleMessage = false;

	/**
	 * reference to the list
	 */
	private ListView list;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// link with an xml layout resource
		setContentView(R.layout.main);

		// Setting up the Alarm Manager
		AlarmManager mgr = (AlarmManager) this
				.getSystemService(Context.ALARM_SERVICE);
		Intent i = new Intent(this, OnAlarmReceiver.class);
		PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0);

		mgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
				SystemClock.elapsedRealtime() + 60000, PERIOD, pi);

		// populate the listview with simple array elements
		list = (ListView) findViewById(R.id.listView);
		list.setAdapter(new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, getResources()
						.getStringArray(R.array.listValues)));

		// register listener on listview for a single click
		list.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Toast.makeText(getApplicationContext(),
						"Selected :" + list.getItemAtPosition(position),
						Toast.LENGTH_SHORT).show();

			}

			public void onNothingSelected(android.widget.AdapterView<?> arg0) {
			};

		});

		// register listener to listview for context menu to show a dialog on
		// selection
		registerForContextMenu(list);
	}

	@Override
	protected void onStart() {
		super.onStart();

		// example of getting preferences in application for use
		prefs = PreferenceManager.getDefaultSharedPreferences(this);
		// lets update the lifecycle boolean preference, false by default
		showLifeCycleMessage = prefs.getBoolean("checkboxPref", false);

		// for demo only show lifecycle of app
		if (showLifeCycleMessage)
			showToast("Lifecycle: onStart");
	}

	@Override
	protected void onStop() {
		super.onStop();

		// for demo only show lifecycle of app
		if (showLifeCycleMessage)
			showToast("Lifecycle: onStop");

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();

		// for demo only show lifecycle of app
		if (showLifeCycleMessage)
			showToast("Lifecycle: onDestroy");

	}

	@Override
	protected void onPause() {
		super.onPause();

		// for demo only show lifecycle of app
		if (showLifeCycleMessage)
			showToast("Lifecycle: onPause");

	}

	@Override
	protected void onRestart() {
		super.onRestart();

		// for demo only show lifecycle of app
		if (showLifeCycleMessage)
			showToast("Lifecycle: onRestart");

	}

	/**
	 * We're catching button clicks here
	 */
	public void onClick(View v) {
		Button b = (Button) v;
		final String message = b.getText().toString();

		switch (v.getId()) {
		case R.id.dinnertime_btn:
		case R.id.bedtime_btn:
		case R.id.sexytime_btn:
			// Send a message in a background thread
			new Thread(new Runnable() {
				public void run() {
					try {
						JSONObject json = new JSONObject();
						final Random randompart = new Random();

						json.put("message", message);
						json.put(
								"nickname",
								prefs.getString("nickname", new String("anon-"
										+ randompart.nextInt(9999))));

						DFHttpClient.post(baseurl + "message", json);
						
						// Tell the main-thread that we are done
						XtimeActivity.this.runOnUiThread(new Runnable(){
							public void run() {
								showToast("Message Sent");
							}
						});
					} catch (JSONException e1) {
						e1.printStackTrace();
					} catch (ApiException e) {
						e.printStackTrace();
					}
				}
				
				 
			}).start();

			break;
		default:
			break;
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		// example of adding an item to the options menu, here for opening
		// preferences
		menu.add(0, ACTIVITY_PREFERENCES, 1, R.string.settings_label);
		return true;
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		boolean bla = super.onMenuItemSelected(featureId, item);

		switch (item.getItemId()) {
		// link the preference option to the preference activity
		case ACTIVITY_PREFERENCES:
			startActivity(new Intent(this, EditPreferences.class));
			return (true);
		}

		return bla;
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		// add the menu items
		menu.add(0, MENU_DIALOG, 1, R.string.show_dialog);
		menu.add(0, MENU_TOAST, 1, R.string.show_toast);
		menu.add(0, MENU_NOTIFICATION, 1, R.string.show_notification);
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		// AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
		// .getMenuInfo();
		switch (item.getItemId()) {
		case MENU_DIALOG:
			showDialog(DIALOG_FROM_LIST);
			return true;
		case MENU_TOAST:
			Toast.makeText(getApplicationContext(), "Toasted!",
					Toast.LENGTH_SHORT).show();
			return true;
		case MENU_NOTIFICATION:
			showNotification();
			return true;
		default:
			return super.onContextItemSelected(item);
		}
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DIALOG_FROM_LIST:
			// create some example dialog here
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle("The Question")
					.setMessage("This is a Dialog?")
					.setCancelable(false)
					.setPositiveButton("Yes",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									showToast("Good Job!");
									dialog.cancel();
								}
							})
					.setNegativeButton("No",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									showToast("Think Again...");
								}
							});
			return builder.create();
		default:
			return super.onCreateDialog(id);

		}
	}

	/**
	 * show a single notification message
	 */
	private void showNotification() {
		NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
		int icon = android.R.drawable.ic_dialog_alert;
		CharSequence tickerText = "Hello";
		long when = System.currentTimeMillis();
		Notification notification = new Notification(icon, tickerText, when);
		CharSequence contentTitle = "My notification";
		CharSequence contentText = "Hello World!";
		Intent notificationIntent = new Intent(this, XtimeActivity.class);
		PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
				notificationIntent, 0);
		notification.setLatestEventInfo(getApplicationContext(), contentTitle,
				contentText, contentIntent);
		mNotificationManager.notify(HELLO_ID, notification);
	}

	/**
	 * show a toast message using the given text
	 * 
	 * @param text Text to show within toast
	 */
	private void showToast(String text) {
		Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
	}
}